package com.gm.commonlib.util.viewUtils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;

import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.recyclerview.widget.RecyclerView;

import com.gm.commonlib.util.AndroidUtil;
import com.gm.commonlib.views.toast.ToastUtil;

import java.util.List;

/**
 * TypedValue是动态类型数据的容器，主要用于盛放resource的值。
 * TypedArray中的函数是获取自定义属性的，
 * Resources中的函数是获取android预置属性的
 */
public class ViewUtil {

    /**
     * todo 支持全面屏
     */
    public static void supportMaxScreen(Activity activity) {
        if (activity == null) {
            return;
        }
        Window window = activity.getWindow();
        if (window == null) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setNavigationBarColor(Color.WHITE);
        }
    }
    /**
     * dip转化像素
     *
     * @param dipValue
     * @return
     */
    public static int dip2px(float dipValue) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);

    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static void setWidth(View view, int size, boolean isDip) {
        if (view != null) {
            ViewGroup.LayoutParams layoutParam = view.getLayoutParams();
            if (layoutParam != null) {
                if (isDip) {
                    layoutParam.width = dp2px(view.getContext(), size);
                } else {
                    layoutParam.width = size;
                }
                view.setLayoutParams(layoutParam);
            }
        }
    }

    /**
     * 只要最外层是LinearLayout，里面的布局你可以随意写，
     * 不管再嵌套多少层其他的布局，比如Relativelayout，都能顺利的显示到地图上。
     */
    public static Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        return Bitmap.createBitmap(cacheBitmap);
    }

    public static int dp2px(Context context, int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
    }

    public static int dp2px(Context context, boolean isDip, int size) {
        if (context != null && isDip) {
            return dp2px(context, size);
        } else {
            return size;
        }
    }

    /**
     * getDimension()是基于当前DisplayMetrics进行转换，获取指定资源id对应的尺寸。文档里并没说这里返回的就是像素，要注意这个函数的返回值是float，像素肯定是int。
     * getDimensionPixelSize()与getDimension()功能类似，不同的是将结果转换为int，并且小数部分四舍五入。
     * getDimensionPixelOffset()与getDimension()功能类似，不同的是将结果转换为int，并且偏移转换（offset conversion，函数命名中的offset是这个意思）是直接截断小数位，即取整（其实就是把float强制转化为int，注意不是四舍五入哦）。
     *
     * @param context
     * @param dimension
     * @return
     */
    public static int getPxFromDimensionRes(Context context, int dimension) {
        if (context != null) {
            return context.getResources().getDimensionPixelOffset(dimension);
        } else {
            return 0;
        }
    }

    public static void setViewClickable(View view, boolean clickable) {
        if (view != null) {
            view.setFocusable(clickable);
            view.setFocusableInTouchMode(clickable);
            view.setClickable(clickable);
            view.setLongClickable(clickable);
            if (view instanceof EditText) {
                EditText editText = (EditText) view;
                //TODO InputType.TYPE_NULL 来禁止手机软键盘
                //TODO InputType.TYPE_CLASS_TEXT 来开启软键盘
                editText.setInputType(clickable ? InputType.TYPE_CLASS_TEXT : InputType.TYPE_NULL);
            }
        }
    }

    public static void setKeyboardTypeToNumber(EditText editText) {
        setKeyboardType(editText, InputType.TYPE_CLASS_NUMBER);
    }

    public static void setKeyboardTypeToText(EditText editText) {
        setKeyboardType(editText, InputType.TYPE_CLASS_TEXT);
    }

    public static void setKeyboardTypeToEmpty(EditText editText, int type) {
        setKeyboardType(editText, InputType.TYPE_NULL);
    }

    public static void setKeyboardType(EditText editText, int type) {
        if (editText != null) {
            editText.setInputType(type);
        }
    }

    public static void setFilters(EditText editText, InputFilter[] inputFilters) {
        if (editText != null && inputFilters != null) {
            editText.setFilters(inputFilters);
        }

    }

    public static boolean isViewClickable(View view) {
        if (view != null) {
            return view.isClickable();
        }
        return false;
    }

    /**
     * 设置textview 的drawable属性
     *
     * @param attention
     * @param drawableId
     */
    public static void setDrawableLeft(Context context, TextView attention, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            attention.setCompoundDrawables(drawable, null, null, null);
        }
    }

    public static void setDrawableRight(Context context, TextView attention, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            attention.setCompoundDrawables(null, null, drawable, null);
        }
    }

    public static void setDrawableLeftAndRight(Context context, TextView attention, int drawableLeftId,int drawableRightId) {
        Drawable leftDrawable = context.getResources().getDrawable(drawableLeftId);
        Drawable rightDrawable = context.getResources().getDrawable(drawableRightId);
        if (leftDrawable != null && rightDrawable!=null) {
            leftDrawable.setBounds(0, 0, leftDrawable.getMinimumWidth(), leftDrawable.getMinimumHeight());
            rightDrawable.setBounds(0, 0, rightDrawable.getMinimumWidth(), rightDrawable.getMinimumHeight());
            attention.setCompoundDrawables(leftDrawable, null, rightDrawable, null);
        }
    }



    /**
     * getDimension和getDimensionPixelOffset的功能类似，都是获取某个dimen的值，
     * 但是如果单位是dp或sp，则需要将其乘以density
     * 如果是px，则不乘。并且getDimension返回float，
     * <p>
     * getDimensionPixelOffset返回int.
     * 而getDimensionPixelSize则不管写的是dp还是sp还是px,都会乘以denstiy.
     */
    public static int getDimensionPixelOffset(Context context, int resId) {
        if (context == null) {
            return 0;
        }
        Resources resources = context.getResources();
        return getIDimensionPixel(resources, resId);
    }

    public static int getIDimensionPixel(Resources resources, int resId) {
        if (resources == null) {
            return 0;
        }
        return resources.getDimensionPixelOffset(resId);
    }

    public static void setPadding(View view, Resources resources,
                                  int leftDimen, int topDimen,
                                  int rightDimen, int bottomDimen) {
        if (view != null && resources != null) {
            view.setPadding(getIDimensionPixel(resources, leftDimen),
                    getIDimensionPixel(resources, topDimen),
                    getIDimensionPixel(resources, rightDimen),
                    getIDimensionPixel(resources, bottomDimen));
        }
    }

    public static void setPadding(View view, boolean isDp, int left, int right, int top, int bottom) {
        if (view != null) {
            Context context = view.getContext();
            view.setPadding(dp2px(context, isDp, left),
                    dp2px(context, isDp, top),
                    dp2px(context, isDp, right),
                    dp2px(context, isDp, bottom));
        }
    }

    /**
     * 设置textview 的drawable属性
     *
     * @param attention
     * @param drawableId
     */
    public static void setDrawableBottom(Context context, TextView attention, int drawableId) {
        Drawable drawable = context.getResources().getDrawable(drawableId);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            attention.setCompoundDrawables(null, null, null, drawable);
        }
    }

    /**
     * @param attention
     */
    public static void cleanDrawable(TextView attention) {
        if (attention != null) {
            attention.setCompoundDrawables(null, null, null, null);
        }
    }


    public static void setTextViewColor(Context context, TextView textView, int colorRes) {
        if (context != null && textView != null) {
            textView.setTextColor(context.getResources().getColor(colorRes));
        }
    }

    public static void setTextViewColor(TextView textView, int colorRes) {
        if (textView != null) {
            Context context = textView.getContext();
            if (context != null) {
                textView.setTextColor(context.getResources().getColor(colorRes));
            }
        }
    }

    public static void setTextViewColorStateList(TextView textView, int colorRes) {
        if (textView != null) {
            Context context = textView.getContext();
            if (context != null) {
                textView.setTextColor(context.getResources().getColorStateList(colorRes));
            }
        }
    }

    public static void setText(View view, int textViewId, CharSequence textString) {
        if (view != null && textViewId != View.NO_ID) {
            setText((TextView) view.findViewById(textViewId), textString);
        }
    }


    public static void setText(TextView text, CharSequence textString) {
        setText(text, textString, true);
    }

    public static void setTextHint(View view, int textViewId, CharSequence textString) {
        if (view != null && textViewId != View.NO_ID) {
            setHint((TextView) view.findViewById(textViewId), textString);
        }
    }

    public static void setTextHint(TextView view, CharSequence textString) {
        if (view != null) {
            setHint(view, textString);
        }
    }

    public static String getText(TextView text) {
        return getText(text, "");
    }

    public static String getText(TextView text, String defaultString) {
        if (text != null) {
            String textContent = text.getText().toString();
            if ("".equals(textContent)) {
                return defaultString;
            }
            return textContent;
        }
        return defaultString;
    }

    public static void setText(TextView text, int stringResId) {
        setText(text, stringResId, true);
    }

    public static void setText(Activity activity, int textId, CharSequence textString) {
        if (activity == null) {
            return;
        }
        View orgView = activity.findViewById(textId);
        if (orgView instanceof TextView) {
            TextView textView = (TextView) orgView;
            setText(textView, textString, true);
        }
    }

    public static void setText(TextView text, CharSequence textString, boolean setEmptyString) {
        if (text != null) {
            if (!TextUtils.isEmpty(textString)) {
                text.setText(textString);
            } else if (setEmptyString) {
                text.setText("");
            }
        }
    }

    public static void setText(TextView text, int stringResId, boolean setEmptyString) {
        if (text != null) {
            if (stringResId != 0) {
                text.setText(stringResId);
            } else if (setEmptyString) {
                text.setText("");
            }
        }
    }

    public static void setText(TextView text, String textString, ValueBindHelper helper) {
        if (text != null) {
            if (TextUtils.isEmpty(textString)) {
                textString = "";
            }
            if (helper != null && helper.bindValue(textString)) {
                text.setText(textString);
            } else if (helper == null) {
                text.setText(textString);
            }
        }
    }

    public static void setTextColor(View view, int textViewId, @ColorRes int colorRes) {
        if (view != null && textViewId != View.NO_ID) {
            setTextViewColor((TextView) view.findViewById(textViewId), colorRes);
        }
    }

    public static void setTextSize(View view, int textViewId, @DimenRes int textSizeDimen) {
        if (view != null && textViewId != View.NO_ID) {
            setTextSize((TextView) view.findViewById(textViewId), textSizeDimen);
        }
    }

    public static void setTextSize(TextView view, @DimenRes int textSizeDimen) {
        if (view != null) {
            setTextSizeValue(view, (int) view.getResources().getDimension(textSizeDimen));
        }
    }

    public static void setTextSizeValue(TextView view, float textSizeDimen) {
        if (view != null) {
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizeDimen);
        }
    }

    /**
     * @param view
     * @param type {@link Typeface#BOLD}
     */
    public static void setTextViewTypeface(TextView view, int type) {
        if (view != null) {
            switch (type) {
                case Typeface.BOLD:
                case Typeface.NORMAL:
                case Typeface.ITALIC:
                case Typeface.BOLD_ITALIC:
                    setTextViewTypeface(view, Typeface.defaultFromStyle(type));
                    break;
            }
        }
    }

    public static void setTextViewTypeface(TextView view, Typeface type) {
        if (view != null) {
            view.setTypeface(type);
        }
    }

    /**
     * TODO 想要让默认输入类型为数字，并且可以切换到其他输入类型
     *
     * @param textView
     * @param inputType 默认输入类型
     *                  TODO                 例如: InputType.TYPE_CLASS_NUMBER： 不改变输入类型，但首先弹出数字键盘
     */
    public static void setEditTextInputType(TextView textView, int inputType) {
        if (textView != null) {
            textView.setRawInputType(inputType);
        }
    }

    public static void setVisibility(Activity activity, int viewId, int visibility) {
        if (activity == null) {
            return;
        }
        View orgView = activity.findViewById(viewId);
        if (orgView != null) {
            orgView.setVisibility(visibility);
        }
    }

    public static int getVisibility(View view) {
        if (view == null) {
            return View.GONE;
        }
        return view.getVisibility();
    }

    public static boolean isViewVisible(View view) {
        if (view == null) {
            return false;
        }
        return view.getVisibility() == View.VISIBLE;
    }


    public static boolean isViewEnabled(View view) {
        if (view == null) {
            return false;
        }
        return view.isEnabled();
    }

    public static void setVisibility(View view, int visibility) {
        if (view != null) {
            switch (visibility) {
                case View.VISIBLE:
                case View.GONE:
                case View.INVISIBLE:
                    view.setVisibility(visibility);
                    break;
            }
        }
    }

    public static void setVisibility(View view, boolean visibility) {
        if (view != null) {
            if (visibility) {
                view.setVisibility(View.VISIBLE);
            } else {
                view.setVisibility(View.GONE);
            }
        }
    }

    public static void setImageBitmap(ImageView imageBitmap, Bitmap bitmap) {
        if (imageBitmap != null && bitmap != null && !bitmap.isRecycled()) {
            imageBitmap.setImageBitmap(bitmap);
        }
    }

    public static void setImageResource(ImageView imageView, int resId) {
        if (imageView != null && resId != 0) {
            imageView.setImageResource(resId);
        }
    }

    /**
     * 设置ImageView饱和度
     *
     * @param imageview  图片控件
     * @param saturation 饱和度:0为纯黑白，饱和度为0；1为饱和度为100，即原图；
     */
    public static void setImageViewSaturation(ImageView imageview, float saturation) {
        if (imageview != null) {
            if (saturation < 0) {
                saturation = 0;
            } else if (saturation > 1) {
                saturation = 1;
            }
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(saturation);// 设置
            ColorMatrixColorFilter grayColorFilter = new ColorMatrixColorFilter(cm);
            imageview.setColorFilter(grayColorFilter);
        }
    }


    public static Drawable createSaturationDrawable(Context context, int resId, float saturation) {
        if (context == null) {
            return null;
        }
        try {
            Drawable mDrawable = context.getResources().getDrawable(resId);
            //Make this drawable mutable.
            //A mutable drawable is guaranteed to not share its state with any other drawable.
            mDrawable.mutate();
            ColorMatrix cm = new ColorMatrix();
            cm.setSaturation(saturation);
            ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
            mDrawable.setColorFilter(cf);
            return mDrawable;
        } catch (Exception e) {
            return null;
        }
    }

    public static <T extends View> T getTypeView(Activity activity, int viewId) {
        if (activity == null) {
            return null;
        }
        View orgView = activity.findViewById(viewId);
        return (T) activity.findViewById(viewId);
    }

    public static void enableView(View view, boolean b) {
        if (view == null) {
            return;
        }
        view.setEnabled(b);
    }

    public static int getColor(Resources resources, int colorId) {
        if (resources == null || colorId == 0) {
            return 0xffffffff;
        }
        return resources.getColor(colorId);
    }

    public static void setOnClickListener(View view, View.OnClickListener listener) {
        if (view != null) {
            view.setOnClickListener(listener);
        }
    }

    public static ColorDrawable getColorDrawable(Resources resources, int colorId) {
        return new ColorDrawable(getColor(resources, colorId));
    }

    /**
     * 设置某个View的margin
     *
     * @param view 需要设置的view
     * @return
     */
    public static ViewGroup.MarginLayoutParams getOrCreateMarginLayoutParams(View view) {
        ViewGroup.MarginLayoutParams marginParams = null;

        if (view != null) {
            ViewGroup.LayoutParams params = view.getLayoutParams();
            //获取view的margin设置参数
            if (params instanceof ViewGroup.MarginLayoutParams) {
                marginParams = (ViewGroup.MarginLayoutParams) params;
            } else if (params instanceof AbsListView.LayoutParams) {
            } else if (params != null) {
                //不存在时创建一个新的参数
                //基于View本身原有的布局参数对象，否则可能丢失一些原本的布局属性.
                marginParams = new ViewGroup.MarginLayoutParams(params);
            } else {
                marginParams = new ViewGroup.MarginLayoutParams(
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
        }

        return marginParams;
    }

    /**
     * 设置某个View的margin
     *
     * @param view   需要设置的view
     * @param isDp   需要设置的数值是否为DP
     * @param left   左边距
     * @param right  右边距
     * @param top    上边距
     * @param bottom 下边距
     * @return
     */
    public static ViewGroup.LayoutParams setMargin(View view, boolean isDp, int left, int right, int top, int bottom) {
        if (view == null) {
            return null;
        }

        ViewGroup.MarginLayoutParams marginParams = getOrCreateMarginLayoutParams(view);
        if (marginParams != null) {
            Context context = view.getContext();
            //根据DP与PX转换计算值,设置margin
            marginParams.setMargins(dp2px(context, isDp, left),
                    dp2px(context, isDp, top),
                    dp2px(context, isDp, right),
                    dp2px(context, isDp, bottom));
            view.setLayoutParams(marginParams);
        }
        return marginParams;
    }



    public static void setHint(TextView textView, CharSequence hintText) {
        if (textView != null) {
            if (TextUtils.isEmpty(hintText)) {
                hintText = "";
            }
            textView.setHint(hintText);
        }
    }

    public static void seWindowBackgroundAlpha(Activity activity, float bgAlpha) {
        seWindowBackgroundAlpha(activity, bgAlpha, false);
    }

    /**
     * 设置当前窗口的透明度
     */
    public static void seWindowBackgroundAlpha(Activity activity, float bgAlpha, boolean flag) {
        if (activity == null) {
            return;
        }
        Window window = activity.getWindow();
        if (window == null) {
            return;
        }
        WindowManager.LayoutParams lp = window.getAttributes();
        if (lp != null) {
            if (flag) {
                window.setBackgroundDrawable(new ColorDrawable(0x000000));
                lp.alpha = bgAlpha; //0-1
                if (bgAlpha == 1) {
                    //TODO 不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
                    activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                } else {
                    //TODO 此行代码主要是解决在华为手机上半透明效果无效的bug
                    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                }
            }
            window.setAttributes(lp);
        }
    }

    public static String convertEnptyWithDefault(String orgValue, String defaultValue) {
        if ("".equals(orgValue) || null == orgValue) {
            return defaultValue;
        }
        return orgValue;
    }

    public static void setAlpha(View view, float alpha) {
        if (view != null && Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            view.setAlpha(alpha);
        }
    }

    public static void setText(TextView textView, SpannableString spannableString) {
        if (textView != null && spannableString != null) {
            textView.setText(spannableString);
        }
    }

    public static void setBackgroundColor(View view, int colorRes) {
        if (view != null) {
            Context context = view.getContext();
            if (context != null) {
                view.setBackgroundColor(context.getResources().getColor(colorRes));
            }
        }
    }

    public static void setBackgroundResource(View view, int resId) {
        if (view != null) {
            Context context = view.getContext();
            if (context != null) {
                view.setBackgroundResource(resId);
            }
        }
    }

    public static void setDividerColor(ListView listView, int colorRes) {
        if (listView != null) {
            Context context = listView.getContext();
            if (context != null) {
                listView.setDivider(ViewUtil.getColorDrawable(context.getResources(), colorRes));
            }
        }
    }

    public static View inflate(Context context, int layout) {
        return inflate(context, layout, null);
    }

    public static View inflate(Context context, int layout, boolean attachParent) {
        return inflate(context, layout, null, attachParent);
    }

    public static View inflate(Context context, int layout, ViewGroup parent) {
        return inflate(context, layout, parent, parent != null);
    }

    public static View inflate(Context context, int layout, ViewGroup parent, boolean attachParent) {
        return LayoutInflater.from(context).inflate(layout, parent, attachParent);
    }

    public static void setWindowAlpha(Activity activity, float alpha) {
        if (activity != null) {
            Window window = activity.getWindow();
            if (window != null) {
                WindowManager.LayoutParams lp = window.getAttributes();
                if (lp != null) {
                    lp.alpha = alpha; //0.0-1.0
                    window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    window.setAttributes(lp);
                }
            }
        }
    }

    /**
     * ScrollView与GridView共用时滚动的处理函数。
     * 适配GridView高度，以避免ScrollView中嵌套GridView时只显示一行。
     *
     * @param gridView
     * @param columns
     */
    public static void setGridViewHeightBasedOnChildren(GridView gridView, int columns, int maxRow) {
        ListAdapter listAdapter = gridView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int items = listAdapter.getCount();
        int rows = 0;

        View listItem = listAdapter.getView(0, null, gridView);
        listItem.measure(0, 0);
        totalHeight = listItem.getMeasuredHeight() + 1;

        float x = 1;
        if (items > columns) {
            x = items / columns;
            if (items % columns != 0) {
                rows = (int) (x + 1);
            } else {
                rows = (int) x;
            }
            if (maxRow > 0 && rows > maxRow) {
                rows = maxRow;
            }
            totalHeight *= rows;
        }

        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight;
        gridView.setLayoutParams(params);
    }

    public static void setBackground(View view, Drawable drawable) {
        if (view == null) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(drawable);
        } else {
            view.setBackgroundDrawable(drawable);
        }
    }

    public interface ValueBindHelper {
        boolean bindValue(String value);
    }

    public static TabHost.TabSpec getTabSpec(TabHost host, String tag) {
        return host
                .newTabSpec(tag)
                .setIndicator(tag);
    }

    public static void setViewVisibility(View view, int visibility) {
        setVisibility(view, visibility);
    }

    public static final int POS_LEFT = 1;
    public static final int POS_TOP = 2;
    public static final int POS_BUTTOM = 3;
    public static final int POS_RIGHT = 4;

    public static void setRadioButtonDrable(TextView view, int type, int id, Context context) {
        try {
            setCompoundDrawables(context, view, type, context.getResources().getDrawable(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setCompoundDrawables(Context context, TextView view, int type, int id) {
        if (context == null) {
            return;
        }
        try {
            setCompoundDrawables(context, view, type, context.getResources().getDrawable(id));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void clearnDrawables(TextView view) {
        view.setCompoundDrawables(null, null, null, null);
    }

    public static void setCompoundDrawables(Context context, TextView view, int type, Drawable drawable) {
        if (context == null) {
            return;
        }
        try {
            if (drawable != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//非常重要，必须设
            }
            switch (type) {
                case POS_LEFT:
                    view.setCompoundDrawables(drawable, null, null, null);// 左边
                    break;
                case POS_TOP:
                    view.setCompoundDrawables(null, drawable, null, null);// 上
                    break;
                case POS_RIGHT:
                    view.setCompoundDrawables(null, null, drawable, null);// 右
                    break;
                case POS_BUTTOM:
                    view.setCompoundDrawables(null, null, null, drawable);// 下
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void bindAndEnableEmptyFiled(TextView input, String value) {
        ViewUtil.setText(input, value);
        ViewUtil.enableView(input, TextUtils.isEmpty(value));
    }

    /**
     * 设置界面透明度
     *
     * @param activity
     * @param alpha
     */
    public static void setActivityAlpha(Activity activity, float alpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = alpha;
        activity.getWindow().setAttributes(lp);

    }

    public static void setViewAlpha(View view) {
        view.setAlpha(0.4f);
    }

    public static void setViewAlpha(View view, float size) {
        view.setAlpha(size);
    }

    public static void setEnableAndHalfAlpha(View view, boolean enable) {
        setViewAlpha(view, enable ? 1f : 0.4f);
        enableView(view, enable);
    }

    public static void setNestedScrollingEnabled(RecyclerView recyclerView) {
        if (recyclerView != null) {
            //TODO android.support.v4.widget.NestedScrollView 嵌套 RecyclerView, 有一个小问题，触摸到RecyclerView的时候滑动还有些粘连的感觉，只需要在代码中设置
            recyclerView.setNestedScrollingEnabled(false);
        }
    }

    public static String getPrompt() {
        return "提示";
    }

    /**
     * 文本增加下划线
     *
     * @param textView
     */
    public static void setTextviewLine(TextView textView) {
        textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        textView.getPaint().setAntiAlias(true);// 抗锯齿
    }

    public static void clearnTextviewLine(TextView textView) {
        textView.getPaint().setFlags(0);
        textView.getPaint().setAntiAlias(true);// 抗锯齿
    }

    /**
     * dp转换成px
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px转换成dp
     */
    public static int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * sp转换成px
     */
    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * px转换成sp
     */
    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }



    public static void copyDrawableBound(Drawable from, Drawable to) {
        if (from != null && to != null) {
            to.setBounds(from.getBounds());
        }
    }

    public static String getTextWithTag(String tag, String... texts) {
        if (texts == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        boolean isFirst = true;
        for (String text : texts) {
            if (!TextUtils.isEmpty(text)) {
                text = text.trim();
                if (isFirst) {
                    stringBuilder.append(text);
                    isFirst = false;
                } else {
                    stringBuilder.append(tag).append(text);
                }
            }
        }
        return stringBuilder.toString().trim();
    }

    public static String getTextWithTag(List<String> datas)
    {
        return getTextWithTag("/",datas);
    }

    public static String getTextWithTag(String tag, List<String> datas) {
        if (datas == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        boolean isFirst = true;
        for (String text : datas) {
            if (!TextUtils.isEmpty(text)) {
                text = text.trim();
                if (isFirst) {
                    stringBuilder.append(text);
                    isFirst = false;
                } else {
                    stringBuilder.append(tag).append(text);
                }
            }
        }
        return stringBuilder.toString().trim();
    }

    public static String getTextByShuTag(String... text) {
        return getTextWithTag(" | ", text);
    }


    public static void copyText(View view, final String msg, final Activity activity) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AndroidUtil.copy(activity, msg);
                ToastUtil.showToast("已复制到剪切板");
            }
        });
    }


}
